package com.wx.security.service;

import com.wx.commons.api.UserApi;
import com.wx.commons.constant.RedisConstant;
import com.wx.commons.entity.RoleOperationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 资源与角色匹配关系管理业务类
 * Created by macro on 2020/6/19.
 */
@Service
public class ResourceServiceImpl {

    private Map<String, List<String>> resourceRolesMap;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserApi userApi;

    @PostConstruct
    public void initData() {
        resourceRolesMap = new TreeMap<>();
        List<RoleOperationInfo> roleOperationInfos = userApi.getRoleOperationInfo();
        Map<String, List<RoleOperationInfo>> roleOperationMap = roleOperationInfos.stream().collect(Collectors.groupingBy((roleOperation) -> roleOperation.getOperationPath() + "_" + roleOperation.getOperationMethod()));
        for (Map.Entry<String, List<RoleOperationInfo>> roleOperationEntry : roleOperationMap.entrySet()) {
            resourceRolesMap.put(roleOperationEntry.getKey(), roleOperationEntry.getValue().stream().map(RoleOperationInfo::getRoleId).collect(Collectors.toList()));
        }
        redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_ROLES_MAP, resourceRolesMap);
    }
}
